<template>
  <el-card class="good-container">
    <template #header>
      <el-form :inline="true" class="demo-form-inline" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="keyWord" placeholder="请输入关键字查询"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="header">
           <el-button type="primary" icon="el-icon-plus" @click="handleAdd" class="mar" style="margin-right:70px;">新增商品</el-button>
            <el-radio-group v-model="isMarketable" size="small" @change="changeMarke">
              <el-radio label="-1" border>全部商品</el-radio>
              <el-radio label="1" border>出售中</el-radio>
              <el-radio label="0" border>下架中</el-radio>
            </el-radio-group>
            <el-button type="primary" icon="el-icon-d-caret" @click="manyChange" class="mar" style="margin-left:70px;" plain>批量上架/下架</el-button>
      </div>
    </template>
    <el-table
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @sort-change="shorChange" 
      >

      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="商品" header-align="center" width="310px">
        <template #default="scope">
        <div class="g_b">
          <img style="width: 80px; height: 80px;margin-right:10px;" :key="scope.row.goods.id" :src="scope.row.goods.goodsImageStore" alt="商品主图">
          <div class="g_p">
            <div class="p_height">{{scope.row.goods.name}}</div>
            <el-tag size="small" type="danger" v-if="scope.row.goods.goodsType==2">自提商品</el-tag>
            <el-tag size="small" type="danger" v-if="scope.row.goods.goodsType==5">超值</el-tag>
          </div>
        </div>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center">
         <template #default="scope">
           <div class="p_height" v-for="(item,index) in scope.row.goodsPinSetList" :key="index">
             <span class="p_mar">{{item.minNum}}份团</span>{{item.price}}
            </div>
        </template>
      </el-table-column>
       <el-table-column label="佣金" width="120" align="center">
           <template #default="scope">
             <a style="cursor: pointer; margin-right: 10px;"></a>
             <div class="p_height" v-for="(item,index) in scope.row.goodsPinSetList" :key="index">{{item.InCome}} </div>
             <a style="cursor: pointer;" v-if="scope.row.goods.InCome" @click="handleIncome(scope.row, false)">设置佣金</a>
             <a style="cursor: pointer;" v-else @click="handleIncome(scope.row,true)">编辑</a>
          </template>
       </el-table-column>
      <el-table-column label="商品库存" align="center" >
         <template #default="scope">
           <div class="p_height" v-for="(item,index) in scope.row.goodsPinSetList" :key="index">
             <span class="p_mar">{{item.minNum}}份团</span>{{item.store}}
            </div>
        </template>
      </el-table-column>
      <el-table-column prop="goods.sales" label="销量" width="100" align="center" sortable='custom'></el-table-column>
      <el-table-column label="上架状态" width="100" align="center">
        <template #default="scope">
          <span style="color: #67C23A;" v-if="scope.row.goods.isMarketable">销售中</span>
          <span style="color: #F56C6C;" v-else>已下架</span>
        </template>
      </el-table-column>
       <el-table-column prop="goods.remark" label="备注" header-align="center" width="100"></el-table-column>
      <el-table-column prop="goods.createTimes" label="上传时间" align="center" width="160" sortable='custom'></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <a style="cursor: pointer; margin-right: 10px" @click="handleEdit(scope.row.goods.id)">修改</a>
          <a style="cursor: pointer; margin-right: 10px" @click="handleStatus(scope.row.goods.id)">备注</a>
          <!-- <a style="cursor: pointer; margin-right: 10px; color:#F56C6C;" v-if="scope.row.goods.isMarketable" @click="handleStatus(scope.row.goods.id, false)">下架</a>
          <a style="cursor: pointer; margin-right: 10px; color: #67C23A;" v-else @click="handleStatus(scope.row.goods.id,true)">上架</a> -->
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page="pageNum"
      @current-change="changePage"
    />
    <el-dialog title="设置佣金" v-model="visible" width="400px" center>
    <el-form :model="incomeForm" label-width="70px" >
      <el-form-item :label="item.label" v-for="(item,index) in goodsPinSet" :key="index">
        <el-input  type="number" :min="0" v-model="incomeForm[item.id]" placeholder="请输入佣金金额"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitIncome">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  </el-card>
  
</template>

<script>
import { onMounted, reactive, ref, toRefs, inject } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {getData} from '@/utils/axios'
import { store } from '@/store'
export default {
  name: 'Glist',
  setup() {
    const multipleTable = ref(null)
    const $filters = inject('$filters')
    const router = useRouter()
    const state = reactive({
      loading: false,
      busbaseId:store.getters.busId,
      tableData: [], // 数据列表
      multipleSelection: [], // 选中项
      total: 0, // 总条数
      pageNum: 1, // 当前页
      pageSize: 10,// 分页大小
      orderType:'createDate',//sales=销量 price=售价 createDate=上架时间(默认) score=评分
      orderBy:'desc',//asc=升序 desc=降序(默认)"
      isMarketable:"-1",//"-1=所有 0=下架 1=上架
      keyWord:'',//"搜索关键字
      visible:false,
      incomeForm:{},
      goodsId:'',
      goodsPinSet:[]
    })
    
    onMounted(() => {
      getGoodList()
    })
    // 获取列表
    const getGoodList = () => {
      state.loading = true
      let params={
          busbaseId:state.busbaseId,
          pageNum: state.pageNum,
          pageSize: state.pageSize,
          orderType:state.orderType,
          orderBy:state.orderBy,
          isMarketable:state.isMarketable,
          keyWord:state.keyWord
        }
       getData('/goods/goodsBus/getGoodsList',params).then(res=>{
                console.log(res.data,1)
                if(res.data.flag){
                  let data=res.data.data.data;
                 for(let i=0;i<data.length;i++){
                     data[i].goods.InCome=true;
                   for(let j=0;j<data[i].goodsPinSetList.length;j++){
                      data[i].goodsPinSetList[j].price=data[i].goodsPinSetList[j].pinMaxPrice==data[i].goodsPinSetList[j].pinMinPrice?`￥${(data[i].goodsPinSetList[j].pinMinPrice/100)}`:`￥${(data[i].goodsPinSetList[j].pinMinPrice/100)}-￥${(data[i].goodsPinSetList[j].pinMaxPrice/100)}`
                      if(data[i].goodsPinSetList[j].tuanInCome==0){
                         data[i].goodsPinSetList[j].InCome='未设置'
                      }else{
                          data[i].goods.InCome=false;
                          data[i].goodsPinSetList[j].InCome=`￥${(data[i].goodsPinSetList[j].tuanInCome/100).toFixed(2)}`
                      }
                   }
                 }
                  state.tableData = data;
                  state.total = res.data.data.total
                  state.pageNum = res.data.data.pageNum
                  state.loading = false
                }
            }) 
    }
    const changeMarke=(val)=>{//切换商品上下架
      console.log(val)
      state.isMarketable=val
       state.pageNum=1;
       getGoodList()
    }
    const onSubmit=()=>{//查询商品
       state.pageNum=1;
       getGoodList()
    }
    const handleAdd = () => {//新增商品
      router.push({ path: '/add' })
    }
   const manyChange=()=>{//批量上下架
     let ids=state.multipleSelection.join(",")
     getData('/goods/goodsBus/batchGoodsMarketable',{ busbaseId:state.busbaseId,ids}).then(res=>{
          console.log(res.data)
          if(res.data.flag){
              ElMessage.success({message:"操作成功",duration:1000})
              getGoodList()
          }
      }) 
   }
   const shorChange=(column)=>{//表格排序
       switch(column.prop) {
            case 'goods.createTimes':
                state.orderType='createDate';
                break;
            case  'goods.sales':
                state.orderType='sales';
                break;   
        }
     state.orderBy=column.order=='ascending'?'asc':'desc'
     state.pageNum=1;
     getGoodList()
   }
   const handleIncome=(good,status)=>{//设置佣金
     console.log(good)
     state.goodsId=good.goods.id;
     state.goodsPinSet=[];
     state.incomeForm={};
     good.goodsPinSetList.forEach(item=>{
       state.goodsPinSet.push({id:item.id,tuanInCome:item.tuanInCome,label:`${item.minNum}份团`})
       if(status&&item.tuanInCome>0){//修改佣金，回显
         state.incomeForm[item.id]=(item.tuanInCome/100).toFixed(2)
       }
     })
     state.visible=true;
   }
   const submitIncome=()=>{//弹框确认,提交
     console.log(state.incomeForm)
     let entriesA=Object.entries(state.incomeForm)
     for(let i=0;i<entriesA.length;i++){
       for(let j=0;j<state.goodsPinSet.length;j++){
          if(entriesA[i][0]==state.goodsPinSet[j].id){
             if(entriesA[i][1]!=''){
               state.goodsPinSet[j].tuanInCome=Number(entriesA[i][1])*100;
               continue
             }
          }
       }
     }
      getData('/goods/goodsBus/setPinSetTuanInCome',{ busbaseId:state.busbaseId,goodsId:state.goodsId,goodsPinSet:JSON.stringify(state.goodsPinSet)}).then(res=>{
                console.log(res.data)
                if(res.data.flag){
                  state.visible=false;
                   ElMessage.success({message:'设置成功',duration:1000})
                   getGoodList()
                }
            }) 
   }
    const handleEdit = (id) => {//修改商品
      router.push({ path: '/add', query: { id } })
    }
    // 选择项
    const handleSelectionChange = (val) => {
      console.log(val)
      state.multipleSelection=[];
      if(val.length>0){
        val.forEach(ele => {
          state.multipleSelection.push(ele.goods.id)
        });
      }
    }
    const changePage = (val) => {//换页
      state.pageNum = val
      getGoodList()
    }
    const handleStatus = (id) => {//备注
     ElMessageBox.prompt('', '商品备注', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType:'text',
        }).then(({ value }) => {
           if(value){
              getData('/goods/goodsBus/setGoodsRemark',{ busbaseId:state.busbaseId,goodsId:id,remark:value}).then(res=>{
                    console.log(res.data)
                    if(res.data.flag){
                      ElMessage.success({message:'备注成功',duration:1000})
                        getGoodList()
                    }
                }) 
           }
        }).catch(() => {});
    }
    return {
      ...toRefs(state),
      multipleTable,
      onSubmit,
      handleAdd,
      handleSelectionChange,
      handleEdit,
      getGoodList,
      changePage,
      handleStatus,
      changeMarke,
      manyChange,
      handleIncome,
      submitIncome,
      shorChange,
    }
  }
}
</script>

<style scoped>
  .good-container {min-height: 100%;}
 
  .p_mar{margin-right: 35px;}
  .header{padding-top: 20px;}
  .el-card.is-always-shadow {min-height: 100%!important;}
  .g_b{width: 100%;overflow: hidden;}
  .g_p{float: right;width: 190px;}
   .p_height{line-height: 40px;}
</style>